﻿//Copyright (c) 2008, Matthew Newman
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
//* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
//* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
//* Neither the name of BestSnowman.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using ProductKeyManager.DB;
using ProductKeyManager.UI;
using System.Globalization;
using System.Data.Linq;

namespace ProductKeyManager
{
    /// <summary>
    /// Interaction logic for NewDialog.xaml
    /// </summary>
    public partial class ProductDialog : Window
    {
        ProductKeyManagerDataContext db;
        ObservableCollection<string> icons = new ObservableCollection<string>();

        /// <summary>
        /// Sets the DB.
        /// </summary>
        /// <value>The DB.</value>
        public ProductKeyManagerDataContext DB
        {
            set { db = value; }
            get { return db; }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProductDialog"/> class.
        /// </summary>
        public ProductDialog()
        {
            this.Closing += new System.ComponentModel.CancelEventHandler(ProductDialog_Closing);
            InitializeComponent();
        }

        /// <summary>
        /// Handles the Closing event of the ProductDialog control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
        private void ProductDialog_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this._Product.Name = txtProductName.Text;
            this._Product.Icon = cmbIcon.SelectedItem.ToString();
            db.SubmitChanges();
        }

        private DialogMode _Mode = DialogMode.NewProduct;

        /// <summary>
        /// Gets or sets the mode.
        /// </summary>
        /// <value>The mode.</value>
        public DialogMode Mode
        {
            get { return this._Mode; }
            set { this._Mode = value; }
        }

        private int _ProductId;

        /// <summary>
        /// Gets or sets the product id.
        /// </summary>
        /// <value>The product id.</value>
        public int ProductId
        {
            get { return _ProductId; }
            set { _ProductId = value; }
        }

        private Product _Product;

        /// <summary>
        /// Gets the product.
        /// </summary>
        /// <value>The product.</value>
        public Product Product
        {
            get { return _Product; }
        }

        /// <summary>
        /// Windows the loaded.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            this.btnNotes.Checked += new RoutedEventHandler(btnNotes_Checked);
            this.btnNotes.Unchecked += new RoutedEventHandler(btnNotes_Unchecked);
            this.lstProdKeys.SelectionChanged += new SelectionChangedEventHandler(lstProdKeys_SelectionChanged);
            switch (this._Mode)
            {
                case DialogMode.EditProduct:
                    this.Title = "Edit Product";
                    break;
                case DialogMode.ViewProduct:
                    this.Title = "View Product Key(s)";
                    this.txtProductName.IsReadOnly = true;
                    this.AddEditToolbar.Visibility = Visibility.Collapsed;
                    this.cmbIcon.IsEnabled = false;
                    break;
                case DialogMode.NewProduct:
                default:
                    this.Title = "New Product";
                    break;
            }
            this.lblProductName.Content = string.Format(CultureInfo.CurrentCulture, "{0}:", "Product Name");

            PopulateIcons();

            SetView();
        }

        /// <summary>
        /// Populates the icons.
        /// </summary>
        private void PopulateIcons()
        {
            icons.Add("Icons/autoList.ico");
            icons.Add("Icons/autorun.ico");
            icons.Add("Icons/cmd.ico");
            icons.Add("Icons/computer.ico");
            icons.Add("Icons/Favorites.ico");
            icons.Add("Icons/Gear.ico");
            icons.Add("Icons/Generic_Application.ico");
            icons.Add("Icons/Generic_Device.ico");
            icons.Add("Icons/Generic_Document.ico");
            icons.Add("Icons/Globe.ico");
            icons.Add("Icons/journal.ico");
            icons.Add("Icons/Keys.ico");
            icons.Add("Icons/Laptop.ico");
            icons.Add("Icons/Monitor.ico");
            icons.Add("Icons/personalization.ico");
            icons.Add("Icons/VPN.ico");
            icons.Add("Icons/SecurityLock.ico");
            this.cmbIcon.DataContext = icons;
        }

        /// <summary>
        /// Handles the SelectionChanged event of the lstProdKeys control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data.</param>
        void lstProdKeys_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.lstProdKeys.SelectedItem == null)
            {
                this.btnRemoveKeyCode.IsEnabled = false;
            }
            else
            {
                this.btnRemoveKeyCode.IsEnabled = true;
            }
        }

        /// <summary>
        /// Sets the view.
        /// </summary>
        private void SetView()
        {
            if (db == null)
            {
                db = ProductKeyManagerDataContext.GetContext();
            }
            if (_ProductId != 0 && _Product == null)
            {
                _Product = (from p in db.Products
                            where p.Id == _ProductId
                            select p).First();
            }
            if (_Product == null)
            {
                _Product = new Product();
                _Product.UserName = Utility.UserInformation.CurrentUser();
            }
            if (_ProductId == 0 && _Product != null)
            {
                _ProductId = _Product.Id;
                if (!string.IsNullOrEmpty(this.txtProductName.Text))
                {
                    _Product.Name = this.txtProductName.Text;
                }
                else
                {
                    _Product.Name = "New Product";
                }
                _Product.Notes = this.txtNotes.Text;
                db.Products.InsertOnSubmit(_Product);
                db.SubmitChanges();
                _ProductId = _Product.Id;
            }

            this.DataContext = _Product;
            this.cmbIcon.SelectedItem = _Product.IconUri.ToString(); ;
            this.lstProdKeys.DataContext = from k in db.Keys where k.ProductId == _Product.Id select k;
            this.AddEditToolbar.DataContext = this.lstProdKeys.DataContext;
        }

        /// <summary>
        /// Handles the Unchecked event of the btnNotes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void btnNotes_Unchecked(object sender, RoutedEventArgs e)
        {
            this.pnlProductNotes.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Handles the Checked event of the btnNotes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void btnNotes_Checked(object sender, RoutedEventArgs e)
        {
            this.pnlProductNotes.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// Adds the key code.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void AddKeyCode(object sender, RoutedEventArgs e)
        {
            ProductKeyManager.DB.Key code = new ProductKeyManager.DB.Key { ProductId = _Product.Id, Code = "New Key", AllocatedTo = "Not Allocated" };
            db.Keys.InsertOnSubmit(code);
            db.SubmitChanges();
            SetView();
            lstProdKeys.SelectedItem = code;
        }

        /// <summary>
        /// Removes the key code.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void RemoveKeyCode(object sender, RoutedEventArgs e)
        {
            if (lstProdKeys.SelectedItem != null)
            {
                DB.Key code = (ProductKeyManager.DB.Key)lstProdKeys.SelectedItem;

                db.Keys.DeleteOnSubmit(code);
                db.SubmitChanges();

                SetView();
            }
        }
    }
}
